<template>
	<view class="uni-column">
		<view class="content" id="content" :style="{height:style.contentViewHeight+'px'}">
			<scroll-view id="scrollview" scroll-y="true" :style="{height:style.contentViewHeight+'px'}" :scroll-with-animation="true"
			 :scroll-top="scrollTop">
				<message-show v-for="(message,index) in messages" :key="index" v-bind:message="message" :id="id" :headImg='headImg'
				 :userimg="userimg"></message-show>
				<view id="bottom"></view>
			</scroll-view>
		</view>
		<view class="foot">
			<chat-input @send-message="getInputMessage"></chat-input>
		</view>
	</view>
</template>

<script>
	import chatInput from '../../components/chatinput.vue';
	import messageShow from '../../components/messageshow.vue';
	import RongIMLib from '../../common/RongIMLib-3.0.5-dev.min.js'
	import store from '../../store/index.js'
	var _self;
	var navi = null
	// var RongIMClient = RongIMLib

	// const appkey = '25wehl3u20ntw'
	// const appSecret = '0n9qu4SBmbQj'
	
	var config = {}
	if (navi) {
		config.navi = navi
	}
	export default {
		components: {
			chatInput,
			messageShow
		},
		data() {
			return {
				style: {
					pageHeight: 0,
					contentViewHeight: 0,
					footViewHeight: 90,
					mitemHeight: 0,
				},
				scrollTop: 0,
				messages: [],
				title: '',
				token: '',
				name: '',
				detail: '',
				id: '',
				headImg: "",
				userimg: '',
				userId:'',
				status:0,
				im:{},
				rongToken:''
			}
		},

		onLoad(option) {
			this.im = store.state.im
			// console.log(store.state.im)
			this.id = option.id
			console.log(id)
			if(option.id){
				this.getOther(option.id)
			}
			if(option.type == 1){
				this.getsever()
			}
			this.getInfo()
			let rongid = uni.getStorageSync('rongid')
			if(rongid){
				this.getToken()
			}else{
				this.getToken()
			}
			
			// this.gethistroy()
			
		},
		created: function() {
			const res = uni.getSystemInfoSync();
			this.style.pageHeight = res.windowHeight;
			this.style.contentViewHeight = res.windowHeight - uni.getSystemInfoSync().screenWidth / 750 * (100); //像素
		},
		methods: {
			//获取个人信息
			getInfo() {
				let id = uni.getStorageSync('userId')
			    // uni.setStorageSync('RuserId', id);
				
				this.$http.get('/userCenter/getUserInfoById', {
					id: id
				}).then(res => {
					if (res.code == '0') {
						this.userimg = res.data.headImg
						// this.userId =res.data.id.toString()

					}
				})
			},
			//获取客服的信息
			getsever(){
				this.$http.get('/public/getService').then(res => {
					if (res.code == 0) {
						this.headImg = res.data.headImg
						this.name = res.data.name
						this.rongToken =res.data.rongToken 
						uni.setStorageSync('RuserId', res.data.id);
						uni.setNavigationBarTitle({
							title: res.data.name
						})
					}else{
						uni.showToast({
							title:res.msg,
							icon:'none',
							duration:2000,
						})
					}
				})
			},
			//获取对方信息
			getOther(id) {
				this.$http.get('/demand/getDemandInfoById', {
					demandId: id
				}).then(res => {
					if (res.code == 0) {
						console.log(res.data.userHead)
						this.headImg = res.data.userHead
						this.name = res.data.userName
						this.userId = res.data.userId.toString()
						uni.setStorageSync('RuserId', res.data.userId);
						console.log(res.data.userId)
						uni.setNavigationBarTitle({
							title: res.data.userName
						})
					}
				})
			},

			// 连接融云
			getToken() {
				let that = this
				var conversationList = []; // 当前已存在的会话列表
				that.im.watch({
					conversation: function(event) {
						console.log(event)
						var updatedConversationList = event.updatedConversationList; // 更新的会话列表
						console.log('更新会话汇总:', updatedConversationList);
						
						console.log('最新会话列表:', that.im.Conversation.merge({
							conversationList,
							updatedConversationList
						}));
					},
					message: function(event) {
						var message = event.message;
						console.log(that.userId)
						console.log('收到新消息:', message);
						
						if(message.content.content)
						 var newStr = message.content.content.indexOf("http");
						
						    if(newStr==0){
						　　　　message.messageType = 'image'
						
						　　 }
						
						that.addMessage('home', message.content.content, false, message.messageType);
						that.scrollToBottom()
					},
					status: function(event) {
						var status = event.status;
						console.log('连接状态码:', status);
						that.status = status
						console.log(status)
						if(status == 0){
							}else if(status ==  6){
								uni.showModal({
									title: '提示',
									content: '您的账号在其他设备上已登录，重新登录',
									success: function (res) {
										if (res.confirm) {
											
											this.im.disconnect().then(function() {
											  console.log('断开链接成功');
											});
											uni.clearStorageSync()
											uni.navigateTo({
												url:'../login/login'
											})
										} else if (res.cancel) {
											console.log('用户点击取消');
										}
									}
								});
								
							}else if(status==34001){
								
						}	
					}
				})
				if(that.status==0){
					let rongToken
					if(this.type == 1){
						rongToken =this.rongToken
					}else{
						rongToken = uni.getStorageSync("rongToken")
					}
					var user = {
						token: rongToken
					}
					this.im.connect(user).then(function(user) {
						uni.setStorageSync('rongid', user.id);
					  console.log('链接成功, 链接用户 id 为: ', user.id);
					 
					}).catch(function(error) {
					  console.log('链接失败: ', error);
					});
					
				}
				
				
			},
			
			//获取消息文本类型
			addMessage(user, content, hasSub, type) {
				var that = this;
				console.log(user)
				that.messages.push({
					user: user,
					content: content,
					hasSub: hasSub,
					type: type
				});
			},
			//发送消息
			serverSendMessage(user, content, hasSub, type){
				 let that = this
				 let id= this.id
				console.log(id)
				var conversation = this.im.Conversation.get({
				  targetId:id.toString(),
				  type: RongIMLib.CONVERSATION_TYPE.PRIVATE
				});
					
				conversation.send({
				  messageType: RongIMLib.MESSAGE_TYPE.TEXT, // 'RC:TxtMsg'
				  content: {
				    content: content // 文本内容
				  }
				}).then(function(message){
				  console.log('发送文字消息成功', message);
				  var newStr=message.content.content.indexOf("http");
				  
				       if(newStr==0){
				  　　　　message.messageType = 'image'
				  
				  　　}
				  that.addMessage('customer', message.content.content, hasSub, message.messageType)
				  
				});
				
			},
			//获取输入框的内容
			getInputMessage(message) { //获取子组件的输入数据
				this.serverSendMessage('customer',message.content,false, message.type)
				
			},
			//获取历史消息
			gethistroy(){
				var conversation = this.im.Conversation.get({
				  targetId: that.userId,
				  type: RongIMLib.CONVERSATION_TYPE.PRIVATE
				});
				var option = {
				  timestrap: +new Date(),
				  count: 20
				};
				conversation.getMessages(option).then(function(result){
				  var list = result.list; // 历史消息列表
				  var hasMore = result.hasMore; // 是否还有历史消息可以获取
				  console.log('获取历史消息成功', list, hasMore);
				});
			},
			scrollToBottom: function() {
				var that = this;
				var query = uni.createSelectorQuery();
				query.selectAll('.m-item').boundingClientRect();
				query.select('#scrollview').boundingClientRect();
				query.exec(function(res) {
					that.style.mitemHeight = 0;
					res[0].forEach(function(rect) {
						// console.info(rect.height);
						that.style.mitemHeight = that.style.mitemHeight + rect.height + 20;
					});
					if (that.style.mitemHeight > that.style.contentViewHeight) {
						that.scrollTop = that.style.mitemHeight - that.style.contentViewHeight;
					}
				});
			},
			


		},
		// onBackPress() {
		// 	this.im.disconnect().then(function() {
		// 	  console.log('断开链接成功');
		// 	});
		// }
	}
</script>

<style scoped>
	.uni-column {
		display: flex;
		flex-direction: column;
	}

	.content {
		display: flex;
		flex: 1;
		margin-bottom: 100rpx;

	}

	.foot {
		position: fixed;
		width: 100%;
		height: 90rpx;
		min-height: 90rpx;
		left: 0px;
		bottom: 0px;
		overflow: hidden;
	}

	.simal {
		width: 20upx;
		height: 20upx;
	}
</style>
